<script lang="ts" setup>
import moment from "moment";
import { deepClone, setLimitCompontentList } from "@/utils";
import Limits from "@/components/limits/Index.vue";
import type { FormInstance } from "element-plus";
import sysConfigApi from "@/api/sysConfigApi";
import { queryQuestionGroupTreeApi } from "@/api/activity";
import { positiveInteger } from "@/utils/commonRegexp";
import LoginLimitDialog from "./components/LoginLimitDialog.vue";

const props = defineProps({
  detail: {
    type: Object,
  },
  actType: {
    type: [String, Number],
    default: 1,
  },
});

const generatePoster: any = inject("generatePoster");
const activityReadonly: boolean = inject("activityReadonly")!;
const payConfigList = ref([] as any);
const form = ref<any>({
  payConfigId: "",
  payType: "",
  generateLoading: false,
  coverUrl: "",
  showOrderType: "current_act",
  loginStyleId: -1,
  externalSmsConfigId: -1, // 外部短信验证码
  loginStyleIdSel: 999,
  externalSmsConfigIdSel: 999,
  loginType: 'sms',
  externalLoginConfigId: -1,
  customerType: null,
  ipPartinLimit: "{num: null, res: null}",
  topUpLimit: "{num: null, res: null, type: null}"
}),
  limitsList = ref<any>(),
  treeSelectData = ref<Array<any>>([]);

const formRef = ref();
// 设置支付平台
const setPayType = (val: any) => {
  let externalPlatformType = val.selected[0].info.externalPlatformType;
  form.value.payType = externalPlatformType;
};

// 获取支付配置
const getConfigList = async () => {
  if (payConfigList.value.length) {
    return;
  }
  let rs: any = await sysConfigApi.getConfigList({ externalType: "pay" });
  if (rs.code == 200) {
    payConfigList.value = rs.payload;
  }
};
watch(
  () => props.detail,
  (val: any) => {
    form.value = Object.assign({}, form.value, val);
     //登录限制数据 黑名单和白名单二选一
    if(form.value.phoneLoginBlacklist||form.value.phoneLoginWhitelist){
      loginLimit.value=1
    }else{
      loginLimit.value=0
    }
    if (!val.startTime) initTime();
    else form.value.time = [val.startTime, val.endTime];

    if (typeof form.value.expOriginal === "string") {
      limitsList.value = form.value.expOriginal
        ? JSON.parse(form.value.expOriginal)
        : {};
    } else limitsList.value = form.value.expOriginal || {};

    if (val.loginStyleId !== -1) {
      form.value['loginStyleIdSel'] = val.loginStyleId || 999
    }

    if (val.externalSmsConfigId !== -1) {
      form.value['externalSmsConfigIdSel'] = val.externalSmsConfigId || 999
    }

    if (val.ipPartinLimit?.length) {
      const _ipPartinLimitModel = JSON.parse(val.ipPartinLimit)
      ipPartinLimitModel.value.num = _ipPartinLimitModel.num;
      ipPartinLimitModel.value.res = _ipPartinLimitModel.res;
    }

    if (val.topUpLimit?.length) {
      const _topUpLimitModel = JSON.parse(val.topUpLimit)
      topUpLimitModel.value.num = _topUpLimitModel.num;
      topUpLimitModel.value.type = _topUpLimitModel.type;
      topUpLimitModel.value.res = _topUpLimitModel.res;
    }
  },
  { deep: true }
);

const rules = {
  name: [
    { required: true, message: "请输入活动名称", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "活动名称请限制在3至20个字符以内",
      trigger: "blur",
    },
  ],
  time: [{ required: true, message: "请选择活动时间", trigger: "change" }],
  // payConfigId: [
  //   { required: true, message: "请选择支付配置", trigger: "change" },
  // ],
  coverUrl: [
    { required: true, message: "请上传活动封面图", trigger: "change" },
  ],
  groupId: [{ required: true, message: "请选择活动分组", trigger: "change" }],
  loginStyleId: [{ required: true, message: "请选择配置", trigger: "change" }],
  externalSmsConfigId: [{ required: true, message: "请选择配置", trigger: "change" }],
  externalLoginConfigId: [{ required: true, message: "请选择配置", trigger: "change" }],
  customerType: [{
    required: true,
    validator(rule: any, val: any, callback: any) {
      if (!sameUserCheckBox.value) {
        callback()
        return
      }

      if (!isEmpty(form.value.customerType)) {
        callback("请选择同一用户类型")
        return
      }

      callback()
    }
  }],
  ipPartinLimit: [{
    required: true,
    validator(rule: any, val: any, callback: any) {
      if (!ipPartinLimitCheckBox.value) {
        callback()
        return
      }

      if (!positiveInteger.test(ipPartinLimitModel.value.num)) {
        callback("请设置参与次数限制，需为正整数")
        return
      }

      if (isEmpty(ipPartinLimitModel.value.res)) {
        callback("请选择超限结果")
        return
      }

      callback()
    }
  }],
  topUpLimit: [{
    required: true,
    validator(rule: any, val: any, callback: any) {
      if (!topUpLimitCheckBox.value) {
        callback()
        return
      }

      if (!positiveInteger.test(topUpLimitModel.value.num)) {
        callback("请设置参与次数限制，需为正整数")
        return
      }

      if (isEmpty(topUpLimitModel.value.type)) {
        callback("请选择参与次数限制")
        return
      }

      if (isEmpty(topUpLimitModel.value.res)) {
        callback("请选择超限结果")
        return
      }

      callback()
    }
  }]
};

const initTime = () => {
  // 初始化活动时间(自然周)
  // let monday: any = moment().weekday(8).format("YYYY/MM/DD"),
  //   sunday: any = moment().day(14).format("YYYY/MM/DD");
  // monday = new Date(`${monday} 00:00:00`);
  // sunday = new Date(`${sunday} 23:59:59`);
  // form.value.time = [monday.getTime(), sunday.getTime()];
  // 初始化活动时间(最近一周)
  let startDay = moment().format("YYYY/MM/DD"),
    endDay = moment().add(7, "days").format("YYYY/MM/DD");
  form.value.time = [
    new Date(`${startDay} 00:00:00`).getTime(),
    new Date(`${endDay} 00:00:00`).getTime(),
  ];
};

const handleGeneratePoster = () => {
  form.value.generateLoading = true;
  generatePoster();
};

// 获取左侧的树结构(无下级)
const getTagGroupTree = async () => {
  let rs = await queryQuestionGroupTreeApi({
    scene: "ACTIVITY",
  });
  if (rs.code === 200) {
    treeSelectData.value = rs.payload;
  }
};

// 防刷配置 同一用户 限制
const sameUserOptions = ref([
  {
    label: '同一用户ID',
    value: 0,
  },
  {
    label: '同一用户ID、同一用户IP',
    value: 1,
  },
]);

// 防刷配置 ip限制方法选项
const validateOptions = ref([
  {
    label: "参与失败",
    value: 0
  },
  {
    label: "滑块验证",
    value: 1
  },
])

const timeLimitOptions = ref([
  {
    label: "每天",
    value: 1
  },
  {
    label: "每周",
    value: 2
  },
  {
    label: "每月",
    value: 3,
  },
  {
    label: "活动期间",
    value: 4
  }
])

// 同一用户 Checkbox
const sameUserCheckBox = computed({
  get() {
    return !isEmpty(form.value.customerType)
  },
  set(newValue) {
    if (newValue) {
      form.value.customerType = 0
    } else {
      form.value.customerType = null
    }
  }
});

// IP限制
const ipPartinLimitModel = ref({
  num: null,
  res: null,
})

// IP限制 CheckBox
const ipPartinLimitCheckBox = computed({
  get() {
    return !isEmpty(ipPartinLimitModel.value.num) || !isEmpty(ipPartinLimitModel.value.res)
  },
  set(newValue) {
    if (newValue) {
      ipPartinLimitModel.value.num = 1
      ipPartinLimitModel.value.res = 0
    } else {
      ipPartinLimitModel.value.num = null
      ipPartinLimitModel.value.res = null
    }
  }
})

// IP限制 sync FORM 
watch(() => ipPartinLimitModel, () => {
  form.value.ipPartinLimit = JSON.stringify(ipPartinLimitModel.value);
}, { deep: true, immediate: true })

// 充值商品充值限制
const topUpLimitModel = ref({
  type: null,
  num: null,
  res: null,
})

// 充值商品充值限制 CheckBox
const topUpLimitCheckBox = computed({
  get() {
    return !isEmpty(topUpLimitModel.value.type) || !isEmpty(topUpLimitModel.value.num) || !isEmpty(topUpLimitModel.value.res)
  },
  set(newValue) {
    if (newValue) {
      topUpLimitModel.value.type = 1
      topUpLimitModel.value.num = 1
      topUpLimitModel.value.res = 0
    } else {
      topUpLimitModel.value.type = null
      topUpLimitModel.value.num = null
      topUpLimitModel.value.res = null
    }
  }
})

// 充值商品充值限制 sync FORM
watch(() => topUpLimitModel, () => {
  form.value.topUpLimit = JSON.stringify(topUpLimitModel.value)
}, { deep: true, immediate: true })

const isEmpty = (val: any) => {
  return val === undefined || val === null
}

const submit = () => {
  return new Promise((resolve, reject) => {
    (formRef.value as FormInstance).validate(
      async (valid, invalidFields: any) => {
        if (valid) {
          let basicForm: any = deepClone(form.value);
          basicForm.startTime = basicForm.time[0];
          basicForm.endTime = basicForm.time[1];
          if (limitsList.value.children && limitsList.value.children.length > 0)
            basicForm.expOriginal = JSON.stringify(limitsList.value);
          else basicForm.expOriginal = "";
          if(loginLimit.value){
            if(!(basicForm.phoneLoginBlacklist||basicForm.phoneLoginWhitelist)){
             return reject("请配置登录限制");
            }
            resolve(basicForm);
          }else{
            resolve(basicForm);
          }
        } else {
          (formRef.value as FormInstance).scrollToField(
            Object.keys(invalidFields)[0]
          );
          reject("请检查基础配置");
        }
      }
    );
  });
};
const setLoginStyleId = (data: any) => {
  console.log('[ data ]', data)
  form.value.loginStyleId = data.selected[0].id
  if (data.selected[0].id !== -1) {
    form.value.loginStyleIdSel = form.value.loginStyleId
  }
}

const setExternalSmsConfigId = (data: any) => {
  form.value.externalSmsConfigId = data.selected[0].id
  if (data.selected[0].id !== -1) {
    form.value.externalSmsConfigIdSel = form.value.externalSmsConfigId
  }
}
const setExternalLoginConfigId = (data: any) => {
  form.value.externalLoginConfigId = data.selected[0].id

}

//登录限制
const loginLimitRef=ref()
const loginLimit=ref(0)
const showLoginLimit=ref(false)
const loginLimitConfirm=({phoneLoginBlacklist,phoneLoginWhitelist})=>{
  if(loginLimit.value){
    if(phoneLoginBlacklist.length){
      form.value.phoneLoginWhitelist=null
      form.value.phoneLoginBlacklist=(phoneLoginBlacklist.map(i=>i.id)).toString()
    }else if(phoneLoginWhitelist.length){
      form.value.phoneLoginBlacklist=null
      form.value.phoneLoginWhitelist=(phoneLoginWhitelist.map(i=>i.id)).toString()
    }
  }else{
    form.value.phoneLoginWhitelist=null
    form.value.phoneLoginBlacklist=null
  }
}
const openLoginLimit=()=>{
  //登录限制数据 黑名单和白名单二选一
  if(form.value.phoneLoginBlacklist){
    loginLimitRef.value?.getSelectedTreeItems({list:form.value.phoneLoginBlacklist,type:1})
  }
  if(form.value.phoneLoginWhitelist){
    loginLimitRef.value?.getSelectedTreeItems({list:form.value.phoneLoginWhitelist,type:2})
  }
  showLoginLimit.value=true
}
watch(loginLimit,(val)=>{
  if(!val){
    form.value.phoneLoginWhitelist=null
    form.value.phoneLoginBlacklist=null
  }
})

onBeforeMount(() => {
  // getConfigList();
  getTagGroupTree();
});

defineExpose({ submit, form });
</script>
<template>
  <el-form ref="formRef" :model="form" :rules="rules" :disabled="activityReadonly" label-width="auto">
    <h3 class="collpase-title">
      基础配置
    </h3>
    <el-form-item label="活动名称：" prop="name">
      <el-input v-model="form.name" maxlength="20" show-word-limit />
    </el-form-item>
    <el-form-item label="活动时间：" prop="time" style="width: 500px">
      <el-date-picker v-model="form.time" type="datetimerange" value-format="x" range-separator="~"
        start-placeholder="开始时间" end-placeholder="结束时间" />
    </el-form-item>
    <el-form-item label="所属分组：" prop="groupId">
      <TreeSelect v-model="form.groupId" :tree-select-data="treeSelectData" :expand-on-click-node="false"
        :check-strictly="true" :tree-props="{ label: 'name', disabled: ((data: any) => { return data.nodeType === 1 }) }"
        placeholder="请选择分组" />
    </el-form-item>
    <el-form-item label="备注：" prop="remark">
      <el-input v-model="form.remark" :autosize="{ minRows: 2 }" type="textarea" maxlength="150" show-word-limit
        placeholder="请输入活动备注" />
    </el-form-item>
    <el-form-item label="封面图：" prop="coverUrl">
      <Upload v-model="form.coverUrl" file-path="act-poster/" list-type="picture-card">
        <el-icon>
          <Plus />
        </el-icon>
      </Upload>
      <el-button type="primary" style="margin-left: 10px" :loading="form.generateLoading" @click="handleGeneratePoster">
        点击生成
      </el-button>
    </el-form-item>


    <el-form-item prop="payConfigId" label="支付配置">
      <!-- <el-select
        v-model="form.payConfigId"
        placeholder="请选择支付配置"
        @change="setPayType"
      >
        <el-option
          v-for="item in payConfigList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select> -->

      <ScSelector v-model="form.payConfigId" placeholder="请选择支付配置" type="config" :params="{ attach: 'pay' }"
        @change-selected="setPayType">
        <template #expand-pop="{ data }">
          <div v-if="data" class="detail-container">
            <div class="detail-text">
              <h3>
                {{ data.info.name }}
              </h3>
            </div>
            <div class="detail-text_line">
              配置类型：{{ data.info.externalTypeName }}
            </div>
            <div class="detail-text_line">
              所属平台：{{ data.info.externalPlatformTypeName }}
            </div>
            <div class="detail-text_line">
              配置标识：{{ data.info.unique }}
            </div>
            <div class="detail-text_line">
              描述：{{ data.info.remark || "暂无" }}
            </div>
          </div>
        </template>
      </ScSelector>
    </el-form-item>

    <el-form-item prop="showOrderType" label="订单数据">
      <el-radio-group v-model="form.showOrderType">
        <el-radio label="current_act">
          当前活动
        </el-radio>
        <el-radio label="current_ins">
          当前机构
        </el-radio>
        <el-radio label="all_act">
          全部活动
        </el-radio>
        <el-radio label="all_order">
          全部订单
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <h3 class="collpase-title">
      参与限制
    </h3>
    <el-form-item label="参与条件">
      <Limits v-model="limitsList" :disabled="activityReadonly" :options="setLimitCompontentList()" />
    </el-form-item>
    <h3 class="collpase-title">
      登录配置
    </h3>
    <el-form-item prop="loginType" label="登录方式">
      <el-radio-group v-model="form.loginType">
        <el-radio label="sms">
          手机号码登录
        </el-radio>
        <el-radio label="external">
          外部授权登录
        </el-radio>
      </el-radio-group>

      <el-form-item v-if="form.loginType == 'external'" label-width="20px" prop="externalLoginConfigId">
        <ScSelector v-model="form.externalLoginConfigId" placeholder="请选择登录页" type="config"
          :params="{ attach: 'userLogin' }" @change-selected="setExternalLoginConfigId">
          <template #expand-pop="{ data }">
            <div v-if="data" class="detail-container">
              <div class="detail-text">
                <h3>
                  {{ data.info.name }}
                </h3>
              </div>
              <div class="detail-text_line">
                配置类型：{{ data.info.externalTypeName }}
              </div>
              <div class="detail-text_line">
                所属平台：{{ data.info.externalPlatformTypeName }}
              </div>
              <div class="detail-text_line">
                配置标识：{{ data.info.unique }}
              </div>
              <div class="detail-text_line">
                描述：{{ data.info.remark || "暂无" }}
              </div>
            </div>
          </template>
        </ScSelector>
      </el-form-item>
    </el-form-item>
    <!-- 登录限制 -->
    <el-form-item label="登录限制">
      <el-switch v-model="loginLimit" inline-prompt active-text="开" inactive-text="关" :active-value="1" :inactive-value="0"/>
      <el-button v-show="loginLimit"
      style="margin-left:8px" link type="primary" @click="openLoginLimit">查看限制规则</el-button>
      <LoginLimitDialog ref="loginLimitRef"
      v-model:show-dialog="showLoginLimit" @confirm="loginLimitConfirm"/>
    </el-form-item>

    <!-- 外部授权 -->

    <div v-if="form.loginType == 'sms'">
      <el-form-item label="登录页面">
        <el-radio-group v-model="form.loginStyleId">
          <el-radio :label="-1">
            系统默认
          </el-radio>
          <el-radio :label="form.loginStyleIdSel">
            自定义
          </el-radio>
        </el-radio-group>
        <el-form-item v-if="form.loginStyleId !== -1" label-width="20px" prop="loginStyleId">
          <ScSelector v-model="form.loginStyleId" placeholder="请选择登录页" type="loginStyle" :params="{}"
            @change-selected="setLoginStyleId">
            <template #expand-pop="{ data }">
              <div v-if="data" class="detail-container">
                <div class="detail-text">
                  <h3>
                    {{ data.info.title }}
                  </h3>
                </div>
                <el-image style="width: 180px; height: 230px" :src="data.info.cover" fit="fill" />
              </div>
            </template>
          </ScSelector>
        </el-form-item>
      </el-form-item>
    </div>
    <el-form-item prop="showOrderType" label="短信配置">
      <el-radio-group v-model="form.externalSmsConfigId">
        <el-radio :label="-1">
          系统默认
        </el-radio>
        <el-radio :label="form.externalSmsConfigIdSel">
          自定义
        </el-radio>
      </el-radio-group>
      <el-form-item v-if="form.externalSmsConfigId !== -1" label-width="20px" prop="externalSmsConfigId">
        <ScSelector v-model="form.externalSmsConfigId" placeholder="请选择验证码" type="config" :params="{ attach: 'sms_code' }"
          @change-selected="setExternalSmsConfigId">
          <template #expand-pop="{ data }">
            <div v-if="data" class="detail-container">
              <div class="detail-text">
                <h3>
                  {{ data.info.name }}
                </h3>
              </div>
              <div class="detail-text_line">
                配置类型：{{ data.info.externalTypeName }}
              </div>
              <div class="detail-text_line">
                所属平台：{{ data.info.externalPlatformTypeName }}
              </div>
              <div class="detail-text_line">
                配置标识：{{ data.info.unique }}
              </div>
              <div class="detail-text_line">
                描述：{{ data.info.remark || "暂无" }}
              </div>
            </div>
          </template>
        </ScSelector>
      </el-form-item>
    </el-form-item>

    <h3 class="collpase-title">
      防刷配置
    </h3>

    <!-- 同一用户限制 -->
    <el-form-item class="common-form-width">
      <el-checkbox v-model="sameUserCheckBox" class="form-block" />

      <el-select v-model="form.customerType" placeholder="请选择同一用户类型" class="form-block">
        <el-option v-for="item in sameUserOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>

      <span class="form-block">满足任一条件视为同一客户</span>
    </el-form-item>

    <!-- IP限制 -->
    <el-form-item prop="ipPartinLimit" class="common-form-width">
      <el-checkbox v-model="ipPartinLimitCheckBox" class="form-block" />

      <span class="form-block">同一个IP每天参与</span>

      <el-input v-model.number="ipPartinLimitModel.num" type="number" :min="1" class="form-block"
        placeholder="请输入参与次数限制" />

      <span class="form-block">次,超过次数</span>

      <el-select v-model="ipPartinLimitModel.res" class="form-block" placeholder="请选择超限结果">
        <el-option v-for="item in validateOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>

    <!-- 充值商品限制 -->
    <el-form-item class="common-form-width" prop="topUpLimit">
      <el-checkbox v-model="topUpLimitCheckBox" class="form-block" />

      <span class="form-block">充值商品同一充值账号</span>

      <el-select v-model="topUpLimitModel.type" placeholder="请选择时间限制类型" class="form-block">
        <el-option v-for="item in timeLimitOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>

      <el-input v-model.number="topUpLimitModel.num" class="form-block" placeholder="请输入参与次数限制" />

      <span class="form-block">次,超过次数</span>

      <el-select v-model="topUpLimitModel.res" class="form-block" placeholder="请选择超限结果">
        <el-option v-for="item in validateOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
  </el-form>
</template>
<style lang="scss" scoped>
.limitTag {
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;

  :deep(.el-tag__content) {
    display: inline-flex;
    align-items: center;
  }
}

.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;

  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
}

:deep(.el-form-item__error) {
  white-space: nowrap;
}

.el-select {
  width: 100%;
}

.detail-container {
  .detail-text_line {
    white-space: nowrap;
  }
}

.common-form-width {
  .form-block {
    margin: 0 5px 10px;
    word-break: keep-all;
    white-space: nowrap;
  }

  :deep(.el-form-item__label-wrap) {
    // margin-left: 150px !important;
    margin-left: 0 !important;
  }

  :deep(.el-form-item__content) {
    // flex-wrap: nowrap;
  }

  :deep(.el-select) {
    width: 200px;
  }

  :deep(.el-input) {
    width: 200px;
  }
}
</style>
